package com.young.servicehosp.service.impl;

import com.young.model.model.hosp.Department;
import com.young.model.vo.hosp.DepartmentQueryVo;
import com.young.servicehosp.repository.DepartmentRepository;
import com.young.servicehosp.service.DepartmentService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
public class DepartmentServiceImpl implements DepartmentService {

    @Autowired
    private DepartmentRepository departmentRepository;

    @Override
    public void saveDepartment(Department department) {
        Department byHoscode = departmentRepository.findByHoscode(department.getHoscode());
        if (byHoscode != null) {
            BeanUtils.copyProperties(department, byHoscode);
            departmentRepository.save(byHoscode);
        } else {
            department.setCreateTime(new Date());
            department.setUpdateTime(new Date());
            department.setIsDeleted(0);
            departmentRepository.save(department);
        }
    }

    @Override
    public Page<Department> selectPage(Integer page, Integer limit, DepartmentQueryVo departmentQueryVo) {
        Sort sort = Sort.by(Sort.Direction.DESC, "createTime");
        Pageable pageable = PageRequest.of(page - 1, limit, sort);

        Department department = new Department();
        BeanUtils.copyProperties(departmentQueryVo,department);
        department.setIsDeleted(0);

        //创建匹配器，就是如何查询条件
        ExampleMatcher exampleMatcher = ExampleMatcher.matching()
                .withStringMatcher(ExampleMatcher.StringMatcher.CONTAINING)//改变默认字符
                .withIgnoreCase(true);//改变默认大小写忽略方式：忽略大小写

        //创建实例
        Example<Department> example = Example.of(department, exampleMatcher);

        Page<Department> pages = departmentRepository.findAll(example, pageable);
        return pages;
    }
}
